package com.lw.nio.channel.socketChannel;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

/**
 * @author LW
 * @2021/9/12 19:51
 */
public class DatagramChannelDemo {

    @Test
    public void send() throws Exception {
        DatagramChannel dc = DatagramChannel.open();
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9999);
        //发送
        while (true) {
            ByteBuffer buffer = ByteBuffer.wrap("发送".getBytes("UTF-8"));
            dc.send(buffer, address);
            System.out.println("发送完成");
            Thread.sleep(1000);
        }
    }

    @Test
    public void recive() throws Exception {
        DatagramChannel dc = DatagramChannel.open();
        InetSocketAddress address = new InetSocketAddress(9999);

        dc.bind(address);
        //接收
        ByteBuffer buffer1 = ByteBuffer.allocate(1024);

        while (true) {
            buffer1.clear();
            SocketAddress receive = dc.receive(buffer1);

            buffer1.flip();
            System.out.println(receive.toString());
            System.out.println(Charset.forName("UTF-8").decode(buffer1));
        }
    }

    //连接读写
    @Test
    public void testConnect() throws Exception {
        DatagramChannel channel = DatagramChannel.open();
        //绑定
        channel.bind(new InetSocketAddress(9999));

        //连接
        channel.connect(new InetSocketAddress("127.0.0.1", 9999));

        channel.write(ByteBuffer.wrap("发送".getBytes("UTF-8")));
        ByteBuffer buffer1 = ByteBuffer.allocate(1024);

        while (true) {
            buffer1.clear();

            channel.read(buffer1);

            buffer1.flip();
            System.out.println(Charset.forName("UTF-8").decode(buffer1));
        }
    }

    public static void main(String[] args) throws Exception {
        DatagramChannel dc = DatagramChannel.open();
        dc.socket().bind(new InetSocketAddress(10086));


        //接收数据
        ByteBuffer buffer = ByteBuffer.allocate(64);
        buffer.clear();
        SocketAddress receive = dc.receive(buffer);


        //发送数据
        ByteBuffer send = ByteBuffer.wrap("发送".getBytes());
        dc.send(send, new InetSocketAddress("127.0.0.1", 10086));

        //连接===UDP不存在真正的连接，这里指的是想特定的服务地址用read和write接收发送数据（只有在connect之后使用）


    }
}
